﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Data.SqlClient;

using CNCSoft.EWinform;
using CNCSoft.EWinform.ControlUtils;
using CNCSoft.EWinform.ERPApps;
using CNCSoft.EWinform.AGrid;
using CNCSoft.EData;

using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

using Common;

namespace CNCSoft.ErpApps.TMS
{
    public partial class frmBaoCaoGiaoVu : Form
    {
        public frmBaoCaoGiaoVu()
        {
            InitializeComponent();
        }
        
        public string strReportTitle;
        public string strReportFile;

        public bool HaveGroup = false;
        public bool HaveParameterGroup = false;

        public string strMaNienHoc = "";
        public string strMaMonKiemTra = "";
        public string strCotDiemThongKe = "";

        public bool bDisplayTreeGroup = false;

        public frmBaoCaoGiaoVu(string _strReportTitle, string _strReportFile)
        {
            InitializeComponent();
            strReportFile = _strReportFile;
            strReportTitle = _strReportTitle;
            txtTuNgay.Text = DateTime.Now.Date.AddDays(-DateTime.Now.Date.Day + 1).ToString("dd/MM/yyyy");
            txtDenNgay.Text = GlobalVariable.WSInfo.WorkingDate.ToString("dd/MM/yyyy");

            rpt.Load(strReportFile);
            PublicFunction.SetDBLogonForReport(rpt);

        }

        public frmBaoCaoGiaoVu(string _strReportTitle, string _strReportFile, DateTime pTuNgay, DateTime pDenNgay)
        {
            InitializeComponent();
            strReportFile = _strReportFile;
            strReportTitle = _strReportTitle;
            txtTuNgay.Text = pTuNgay.ToString("dd/MM/yyyy")  ;
            txtDenNgay.Text = pDenNgay.ToString("dd/MM/yyyy");

            rpt.Load(strReportFile);
            PublicFunction.SetDBLogonForReport(rpt);

        }

        private void frmBaoCaoGiaoVu_Load(object sender, EventArgs e)
        {
            try
            {
                lblReportName.Text = strReportTitle;
                this.Text = this.Text + " - " + strReportTitle;

                cmdInNguyenlop.Visible = (strReportFile.IndexOf("Report_Giaovu_PhieuDiemCaNhan") > 0);

                //Kiem tra tham so cua report, neu ko co thi disable control truyen tham so tuong ung
                ParameterField pfLop = rpt.ParameterFields.Find("@pMaLop", "");
                ParameterField pfMon = rpt.ParameterFields.Find("@pMaMonKiemTra", "");
                ParameterField pfCotDiemThongKe = rpt.ParameterFields.Find("@pCotDiemThongKe", "");
                ParameterField pfMaHocTap = rpt.ParameterFields.Find("@pMaHocTap", "");
                ParameterField pfMaHocKy = rpt.ParameterFields.Find("@pMaHocKy", "");
                ParameterField pfTuNgayDenNgay = rpt.ParameterFields.Find("@pTuNgay", "");

                panelTuNgayDenNgay.Visible = (pfTuNgayDenNgay != null);
                //pfMaHocKy = rpt.ParameterFields.Find("@pHocKy1", "");
                txtMaLop.Enabled = (pfLop != null || pfMaHocTap != null);
                txtEnquiryNumber.Enabled = (pfMaHocTap != null);
                txtMaMonKiemTra.Enabled = (pfMon != null && strMaMonKiemTra !="");
                cboCotDiemThongke.Enabled = (pfCotDiemThongKe != null);   cboCotDiemThongke.SelectedIndex = 0;
                chkHK1.Enabled = (pfMaHocKy != null); chkHK2.Enabled = (pfMaHocKy != null);

                txtMaNienHoc.Text = strMaNienHoc =="" ? GlobalVariable.WSInfo.getAppProperty("MaNienHocDefault") : strMaNienHoc ;

                //Co so (User thoc Co so nao chi co quyen check/uncheck co so do   (nguoi nao de NULL xem nhu *  - VIP)
                string strCoSoOfUser = (SQLHelper.ExecuteScalar(GlobalVariable.WSInfo.ConnectionString,
                                "select isnull(Position, '*') from SYS_List_User where UserID='" + GlobalVariable.WSInfo.UserID + "'")).ToString().Replace("CS", "");
                chkCS1.Checked = false; chkCS1.Enabled = false;
                chkCS2.Checked = false; chkCS2.Enabled = false;
                if (strCoSoOfUser == "1")
                {
                    chkCS1.Enabled = true; 
                    chkCS1.Checked = true;
                }
                if (strCoSoOfUser == "2")
                {
                    chkCS2.Enabled = true;
                    chkCS2.Checked = true;
                }
                //Xem duoc tat ca (VIP)
                if (strCoSoOfUser == "*")
                {
                    chkCS1.Enabled = true; chkCS2.Enabled = true;
                    chkCS1.Checked= true; chkCS2.Checked = true;
                }

                //Gan danh sach field report dong vao combobox tuong ung voi tung report
                if (HaveGroup)
                    SetComboDynamicGroup();

                
                //panelXem.Left = panelTenBaoCao.Left + panelTenBaoCao.Width + 50;

                //if (HaveGroup)
                //{
                //    panel_HocVien.Visible = false;
                //}
                //else
                //    txtMaLop.Focus();

                cmdXem_Click(sender, e);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //Load report
        ReportDocument rpt = new ReportDocument();


        private void cmdXem_Click(object sender, EventArgs e)
        {
            cmdXem.Enabled = false;
            try
            {
                //Bang diem theo HK hay theo Ca Nam
                if (strReportFile.IndexOf("Report_Giaovu_BangDiem_Mon") > 0)
                {
                    if (chkHK1.Checked && chkHK2.Checked)
                    {
                        rpt.Load(strReportFile.Replace("Mon.rpt", "Mon_CaNam.rpt"));
                        PublicFunction.SetDBLogonForReport(rpt);
                    }
                    else
                    {
                        rpt.Load(strReportFile);
                        PublicFunction.SetDBLogonForReport(rpt);
                    }
                }
                
                //Bang diem tong hop co cac mau khac nhau giua cac cap (khac cot diem)
                if (txtMaLop.Text !="" &&  strReportFile.IndexOf("Report_Giaovu_BangDiemTongHopTheoMon") > 0)
                {
                    string strMaKhoi = SQLHelper.ExecuteScalar(GlobalVariable.WSInfo.ConnectionString, "SELECT MaKhoi FROM DM_LOP WHERE MaLop ='" + txtMaLop.Text + "'").ToString();
                    string strBangDiemTH_HK = SQLHelper.ExecuteScalar(GlobalVariable.WSInfo.ConnectionString, "SELECT BangDiemTH_HK FROM RP_LOP_LSTReport where MaKhoi = '" + strMaKhoi + "'").ToString();
                    string strBangDiemTH_CaNam = SQLHelper.ExecuteScalar(GlobalVariable.WSInfo.ConnectionString, "SELECT BangDiemTH_CaNam FROM RP_LOP_LSTReport where MaKhoi = '" + strMaKhoi + "'").ToString();

                    if (chkHK1.Enabled)
                        strReportFile = Application.StartupPath + "\\Report\\" + strBangDiemTH_HK ;
                    else
                        strReportFile = Application.StartupPath + "\\Report\\" + strBangDiemTH_CaNam;
                    
                    rpt.Load(strReportFile);
                    PublicFunction.SetDBLogonForReport(rpt);
                }
                

                //Set parameter
                PublicFunction.SetParameter(rpt, "@pTuNgay", txtTuNgay.getDateValue());
                PublicFunction.SetParameter(rpt, "@pDenNgay", txtDenNgay.getDateValue());
                PublicFunction.SetParameter(rpt, "pThoiGian", ReportUtilities.ReportUtilities.ThoiGianDep(txtTuNgay.getDateValue(), txtDenNgay.getDateValue()));
                PublicFunction.SetParameter(rpt, "pMoRongDong", chkMoRongDong.Checked);
                
                //Cac tham so lien quan den Lop, Hoc Ky
                PublicFunction.SetParameter(rpt, "@pMaNienHoc", txtMaNienHoc.Text);
                PublicFunction.SetParameter(rpt, "@pCS1",chkCS1.Checked );
                PublicFunction.SetParameter(rpt, "@pCS2", chkCS2.Checked);
                PublicFunction.SetParameter(rpt, "@pMaLop", txtMaLop.Text);
                PublicFunction.SetParameter(rpt, "@pMaHocTap", txtEnquiryNumber.Text);
                PublicFunction.SetParameter(rpt, "@pMaMonKiemTra", txtMaMonKiemTra.Text);
                PublicFunction.SetParameter(rpt, "@pCotDiemThongKe", cboCotDiemThongke.Text);
                PublicFunction.SetParameter(rpt, "@pMaHocKy", "");
                if (chkHK1.Checked)
                    PublicFunction.SetParameter(rpt, "@pMaHocKy", "1");
                if (chkHK2.Checked)
                    PublicFunction.SetParameter(rpt, "@pMaHocKy", "2");
                if (chkHK1.Checked && chkHK2.Checked)
                    PublicFunction.SetParameter(rpt, "@pMaHocKy", "CN");  //Ca Nam

                PublicFunction.SetParameter(rpt, "@pDanhHieuThiDua", strMaMonKiemTra);  // Muon bien strMaMonKiemTra lam de gan dau vao khi goi form cho tham so DHTD

                PublicFunction.SetParameter(rpt, "pGVCN", " ");
                PublicFunction.SetParameter(rpt, "pGVCN", SQLHelper.ExecuteScalar(GlobalVariable.WSInfo.ConnectionString, 
                    "SELECT TenGiaoVien FROM DM_LOP join DM_GIAOVIEN on DM_LOP.MaGiaoVien = DM_GIAOVIEN.MaGiaoVien where MaLop = '" + txtMaLop.Text + "'"));
                //PublicFunction.SetParameter(rpt, "pAcademicHead", GlobalVariable.WSInfo["Sys.UserName.AcademicHead"]);

                //Tjam so cho 2 ma nien hoc
                ParameterField pfMaNienHoc_CuMoi = rpt.ParameterFields.Find("@pMaNienHocCu", "");
                if (pfMaNienHoc_CuMoi != null)
                {
                    PublicFunction.SetParameter(rpt, "@pMaNienHocCu", GlobalVariable.WSInfo.getAppProperty("MaNienHocDefault"));
                    PublicFunction.SetParameter(rpt, "@pMaNienHocMoi", GlobalVariable.WSInfo.getAppProperty("MaNienHocMoi"));
                }


                //Xac dinh parameter cua group
                if (cboFieldNameGroup.SelectedIndex != -1)
                {
                    string strFieldName = ((DataRowView)cboFieldNameGroup.Items[cboFieldNameGroup.SelectedIndex])["GroupFieldDynamic"].ToString();
                    string strGroupName = ((DataRowView)cboFieldNameGroup.Items[cboFieldNameGroup.SelectedIndex])["GroupFieldName"].ToString();
                    PublicFunction.SetParameter(rpt, "@pFieldGroup", strFieldName);
                    PublicFunction.SetParameter(rpt, "@pFieldGroupName", strGroupName);
                }
                else
                {
                    PublicFunction.SetParameter(rpt, "@pFieldGroup", "");
                    PublicFunction.SetParameter(rpt, "@pFieldGroupName", "");
                }
               
                //Gan report source
                CRViewer.ReportSource = rpt;

                if (bDisplayTreeGroup)
                    CRViewer.ToolPanelView = CrystalDecisions.Windows.Forms.ToolPanelViewType.GroupTree;
                    

            }
            catch (Exception ex)
            {
                cmdXem.Enabled = true;
                MessageBox.Show(ex.Message, "cmdXem error!");
            }
            cmdXem.Enabled = true;
        }


        private void SetComboDynamicGroup()
        {
            panelGroup.Visible = false;
            try
            {
                DataTable db = new DataTable("TBGropup");
                strReportFile = strReportFile.Replace(Application.StartupPath + "\\Report\\", "").Replace(".rpt","") ;                  
                SQLHelper.Fill(db, GlobalVariable.WSInfo.ConnectionString, "SELECT * FROM RP_LSTREPORT_DYNAMICGROUP WHERE ReportFileName = '" + strReportFile + "'");
                this.cboFieldNameGroup.DataSource = db;
                this.cboFieldNameGroup.DisplayMember = "Description";
                this.cboFieldNameGroup.ValueMember = "GroupFieldDynamic";
                cboFieldNameGroup.SelectedIndex = 0;
                panelGroup.Visible = true;
            }
            catch (Exception ex)
            {
                panelGroup.Visible = true;
                MessageBox.Show(ex.Message, "SetComboDynamicGroup");
            }
        }

        private void chkMoRongDong_CheckedChanged(object sender, EventArgs e)
        {
            cmdXem_Click(cmdXem, e);
        }

        
      

        private void cboFieldNameGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmdXem_Click(cmdXem, e);
        }

        private void frmBaoCaoGiaoVu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.SelectNextControl(this.ActiveControl, true, true, true, true);
            }
            else if (e.KeyCode == Keys.Escape)
            {
                this.SelectNextControl(this.ActiveControl, true, false, true, true);
            }
        }

        private void cmdEmail_Click(object sender, EventArgs e)
        {
            if (!System.IO.Directory.Exists(Application.StartupPath + "\\PDF"))
                System.IO.Directory.CreateDirectory(Application.StartupPath + "\\PDF");
            string strPDFFile = strReportFile.Replace(Application.StartupPath + "\\Report\\", "").Replace(".rpt", ".pdf") ;
            string pdfFile = Application.StartupPath + "\\PDF\\" + strPDFFile;
            try
            {
                ExportOptions CrExportOptions;
                DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
                PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
                CrDiskFileDestinationOptions.DiskFileName = pdfFile;
                CrExportOptions = rpt.ExportOptions;
                CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
                CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
                CrExportOptions.FormatOptions = CrFormatTypeOptions;
                rpt.Export();

                //Send mail
                try
                {
                    string strEmailAddressTo = "";
                    object oEmail =  SQLHelper.ExecuteScalar(GlobalVariable.WSInfo.ConnectionString, "SELECT isnull(Email,'') as Email FROM Enquiry WHERE EnquiryNumber = '" + txtEnquiryNumber.Text + "'");
                    if (oEmail != null)
                        strEmailAddressTo = oEmail.ToString();
                    System.Diagnostics.Process.Start("Outlook.exe", "/c ipm.note /m " + strEmailAddressTo + " /a " + pdfFile);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void txtMaLop_TextChanged(object sender, EventArgs e)
        {
            txtEnquiryNumber.Text = "";

            txtEnquiryNumber.RefField = "MaHocTap" ;

            txtEnquiryNumber.RefTable = " (SELECT top 200 MaHocTap, HoLot + ' ' + Ten as HoTen From HOCSINH_LOP " +
                                        "  join HOCSINH on HOCSINH_LOP.MaHocSinh = HOCSINH.MaHocSinh " +
                                        " where MaLop = '" + txtMaLop.Text + "' order by STT_SoCai )   as DM ";
        }

        private void txtMaNienHoc_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string strCS = "";
                if (chkCS1.Checked) strCS = "'1'";
                if (chkCS2.Checked) strCS = "'2'";
                if (chkCS1.Checked && chkCS2.Checked) strCS = "'1', '2'";

                txtMaLop.RefTable = " (SELECT top 200 * FROM DM_LOP WHERE MaNienHoc = '" + txtMaNienHoc.Text + "'" +
                                     " AND MaCoSo IN (" + strCS + ") order by makhoi desc, STT) as LOP ";

            }

            catch { }
        }

        private void cmdInNguyenlop_Click(object sender, EventArgs e)
        {
            Academic.frmInNguyenLop frmINL = new Academic.frmInNguyenLop(Application.StartupPath + "\\Report\\Report_Giaovu_PhieuDiemCaNhan.rpt", txtMaLop.Text);
            frmINL.ShowDialog();
            frmINL.Dispose();
        }


       
    }
}
